<template>
  <div class="student-detail">
    <div class="search">
      <el-input
        class="student-name-input"
        v-model="studentName"
        placeholder="搜索学生"
        @change="onSearch"
      />
      <el-input
        type="number"
        v-model.number="searchValue"
        :max="100"
        :min="0"
        placeholder="请输入0-100内数字"
        class="input-with-select"
        @change="onSearch"
      >
        <template #prepend>
          <el-select
            v-model="selectScoreRate"
            placeholder="Select"
            class="select-with-input"
          >
            <el-option label="正确率高于" value="1" />
            <el-option label="正确率低于" value="2" />
          </el-select>
        </template>
        <template #append>%</template>
      </el-input>
      <el-input
        type="number"
        v-model.number="searchQuestionCount"
        style="max-width: 13.8vw"
        placeholder="请输入习题量"
        class="input-with-select"
        @change="onSearch"
      >
        <template #prepend>
          <el-select
            v-model="selectQuestionCount"
            placeholder="Select"
            class="select-with-input"
          >
            <el-option label="习题量高于" value="1" />
            <el-option label="习题量低于" value="2" />
          </el-select>
        </template>
      </el-input>
      <el-button class="search-btn" @click="onSearch">搜索</el-button>
      <div class="operator">
        <template v-if="isCreateTarget"> </template>
        <div
          class="delete-button default"
          v-if="curClassType === CLASS_TYPE.TargetClass"
          @click="deletePopupVisible = true"
        >
          删除靶向班
        </div>
        <div
          class="create-button default"
          :class="{ 'can-create': selectedRow.length > 0 }"
          @click="onCreate"
        >
          创建靶向班
        </div>
        <div class="selected-text" v-if="selectedRow.length > 0">
          <span>已选： {{ selectedRow.length }}人</span>
          <ul class="student-list" v-if="selectedRow.length">
            <li
              class="name-item"
              v-for="(item, index) in selectedRow"
              :key="index"
            >
              {{ item.studentName }}
            </li>
          </ul>
        </div>
      </div>
    </div>
    <a-table
      v-loading="isLoading"
      :columns="columns"
      :dataSource="tableData"
      rowKey="student_id"
      :customRow
      :rowSelection="{
        selectedRowKeys: selectedRowKeys,
        onChange: handleSelectionChange,
        columnWidth: '3%'
      }"
      :locale="{
        emptyText: '暂无数据',
        cancelSort: '点击取消排序',
        triggerAsc: '点击升序',
        triggerDesc: '点击降序'
      }"
      :pagination="false"
      :scroll="{ y: '73vh' }"
    />

    <create-target-class
      :visible="createVisible"
      :studentList="selectedRow"
      :schoolId="userInfo.school_id"
      :teacherId="userInfo.userId"
      @close="handleClose"
    />
  </div>
</template>

<script setup>
import {
  ref,
  onBeforeMount,
  computed,
  watch,
  onMounted,
  onBeforeUnmount,
  h,
  nextTick
} from 'vue'

import { useRoute } from 'vue-router'
import router from '@/router'
import { useAuthStore } from '@/stores'

import CreateTargetClass from '@/views/class-manage/cpns/CreateTargetClass.vue'

import { ElMessage } from 'element-plus'

import { useKnowledgeStore } from '@/stores/knowledge-store'

defineProps({
  isLoading: {
    type: Boolean,
    default: false
  }
})

const route = useRoute()

const { userInfo, getTeachingInfo } = useAuthStore()

const knowledgeStore = useKnowledgeStore()

const CLASS_TYPE = {
  Other: 'class_category|1000',
  AdminClass: 'class_category|1001',
  TeachClass: 'class_category|1002',
  TargetClass: 'target'
}

const columns = [
  {
    title: '学生',
    dataIndex: 'student_name',
    key: 'student_name',
    align: 'center',
    width: '20%'
  },
  {
    title: '综合(题目去重)',
    dataIndex: 'rate',
    key: 'rate',
    align: 'center',
    width: '20%',
    customRender: ({ text, record }) => {
      if (record.rate === 0 && record.question_count === 0) return '--'
      return h('div', {}, [
        h('span', {}, text ? `${(text * 100).toFixed(2)}%` : '0.00%'),
        h(
          'span',
          {
            style: {
              'margin-left': '10px'
            }
          },
          `${record.question_count}题`
        )
      ])
    },
    sorter: (a, b) => a.rate - b.rate
  },
  {
    title: '考试',
    align: 'center',
    width: '20%',
    customRender: ({ record }) => {
      return renderFn(record, 2)
    },
    sorter: (a, b) => a.rate - b.rate
  },
  {
    title: '任务练',
    align: 'center',
    width: '20%',
    customRender: ({ record }) => {
      return renderFn(record, 3)
    },
    sorter: (a, b) => a.rate - b.rate
  },
  {
    title: '作业',
    align: 'center',
    width: '20%',
    customRender: ({ record }) => {
      return renderFn(record, 1)
    },
    sorter: (a, b) => a.rate - b.rate
  },
  {
    title: '自学',
    align: 'center',
    width: '20%',
    customRender: ({ record }) => {
      return renderFn(record, 4)
    },
    sorter: (a, b) => a.rate - b.rate
  }
]

const renderFn = (record, from) => {
  const current = (record.task_info || []).find(item => item.task_from === from)
  if (current.rate === 0 && current?.answer_count === 0) return '--'
  return h('div', {}, [
    h(
      'span',
      {},
      current?.rate ? `${(current.rate * 100).toFixed(2)}%` : '0.00%'
    ),
    h(
      'span',
      {
        style: {
          'margin-left': '10px'
        }
      },
      `${current?.answer_count || 0}题`
    )
  ])
}

const selectedRowKeys = ref([])

const studentName = ref('')
const selectScoreRate = ref('1')
const searchValue = ref('')
const searchQuestionCount = ref('')
const selectQuestionCount = ref('1')

const tableData = ref([])

const selectedRow = ref([])

const handleSelectionChange = (keys, selectedRows) => {
  console.log(selectedRows)

  selectedRowKeys.value = keys
  console.log('选择的', keys)
  selectedRow.value = selectedRows.map(item => ({
    key: item.student_id,
    studentName: item.student_name,
    gradeId: route.query.grade_id
  }))
}

const customRow = row => {
  return {
    onClick: () => {
      console.log(row)
      console.log(route.query)

      const query = {
        ...route.query,
        studentId: row.student_id,
        studentName: row.student_name
      }

      const newRoute = router.resolve({
        name: 'knowledge-point-detail',
        query: query
      })

      window.open(newRoute.href, '_blank')
    }
  }
}
const fullData = ref([])

const searchStudent = data => {
  if (!studentName.value) return data
  return data.filter(item => item.student_name.includes(studentName.value))
}

const searchStudentByRate = data => {
  console.log('搜索', searchValue.value)
  if (!searchValue.value) return data

  if (searchValue.value > 100) {
    searchValue.value = 100
    ElMessage.warning('最大正确率100%')
  }
  if (searchValue.value < 0) {
    searchValue.value = 0
    ElMessage.warning('最小正确率0%')
  }

  return data.filter(item => {
    const rate = item.rate * 100
    return selectScoreRate.value === '1'
      ? rate >= searchValue.value
      : rate <= searchValue.value
  })
}

const searchStudentByCount = data => {
  console.log('搜索', searchQuestionCount.value)
  if (!searchQuestionCount.value && searchQuestionCount.value !== '0')
    return data

  return data.filter(item => {
    return selectQuestionCount.value === '1'
      ? item.question_count >= searchQuestionCount.value
      : item.question_count <= searchQuestionCount.value
  })
}

const onSearch = () => {
  let filteredData = fullData.value

  if (
    !studentName.value &&
    searchValue.value === '' &&
    searchQuestionCount.value === 0
  ) {
    tableData.value = fullData.value
    return
  }

  filteredData = searchStudent(filteredData)
  filteredData = searchStudentByRate(filteredData)
  filteredData = searchStudentByCount(filteredData)

  tableData.value = filteredData
}

// 全局监听回车事件
const handleKeydown = event => {
  if (event.key !== 'Enter') return
  onSearch()
}

onMounted(() => {
  window.addEventListener('keydown', handleKeydown)
})

onBeforeUnmount(() => {
  window.removeEventListener('keydown', handleKeydown)
})

onBeforeMount(async () => {
  tableData.value = knowledgeStore.studentSituationData
  fullData.value = knowledgeStore.studentSituationData
})

watch(
  () => knowledgeStore.studentSituationData,
  async () => {
    // 应为侧边栏的StudentStatus.vue组件已经请求并存入到store中这个组件就没必要重复请求了
    const res = JSON.parse(JSON.stringify(knowledgeStore.studentSituationData))

    tableData.value = res
    fullData.value = res
  }
)

onMounted(() => {
  // 滚动到表格
  const row = document.querySelector('.ant-table-row-selected')
  if (row) {
    row.scrollIntoView({ behavior: 'smooth' })
  }
})

watch(
  () => knowledgeStore.selectedStudent,
  async () => {
    selectedRowKeys.value = knowledgeStore.selectedStudent.map(
      item => item.student_id
    )
    handleSelectionChange(selectedRowKeys.value, knowledgeStore.selectedStudent)
    await nextTick()
    if (!knowledgeStore.selectedStudent.length) {
      document.querySelector('.ant-table-row').scrollIntoView({
        behavior: 'smooth'
      })

      return
    }
    const row = document.querySelector('.ant-table-row-selected')
    if (row) {
      row.scrollIntoView({ behavior: 'smooth' })
    }
  },
  {
    immediate: true
  }
)

const curClassType = computed(() => route.query.class_type)

/**
 * 展示创建弹窗
 */
const createVisible = ref(false)
const isCreateTarget = ref(false)
const onCreate = () => {
  if (!isCreateTarget.value) {
    isCreateTarget.value = true
    return
  }
  if (!selectedRow.value.length && isCreateTarget.value) {
    ElMessage.warning('请选择学生')
    return
  }
  createVisible.value = true
}

const handleClose = message => {
  createVisible.value = false
  if (message === 'refresh') {
    getTeachingInfo()
  }
}
</script>

<style lang="less" scoped>
.student-detail {
  display: flex;
  flex-direction: column;
  height: 100%;

  .search {
    display: flex;
    align-items: center;
    gap: 13px;
    height: 30px;
    margin-top: 10px;
    margin-bottom: 20px;
    :deep(.el-select) {
      width: 115px !important;
    }

    .student-name-input {
      width: 100px;
    }

    .input-with-select {
      width: 370px;

      .select-with-input {
        width: 130px;
      }
    }

    :deep(.el-input__inner) {
      font-size: 14px;

      &::placeholder {
        font-size: 14px;
      }
    }

    .search-btn {
      font-size: 14px;
      width: 76px;
      height: 30px;
      color: #fff;
      background-color: @color-brand-regular;

      &:hover {
        background-color: @color-brand-checked;
      }
    }
    .operator {
      display: flex;
      align-items: center;
      height: 100%;
      .selected-text {
        position: relative;
        font-weight: 500;
        padding-left: 10px;
        cursor: pointer;
        &:hover .student-list {
          display: block;
        }

        .student-list {
          display: none;
          min-width: 83px;
          padding: 0 5px;
          position: absolute;
          z-index: 999;
          top: 30px;
          left: 0;
          padding-top: 30px;
          background: url('@/assets/images/workbench/back-block.png') no-repeat
            center;
          background-color: #fff;
          background-size: 100% 100%;

          .name-item {
            text-align: center;
            margin-bottom: 30px;
          }
        }
      }

      .cancel-text {
        font-weight: 500;
        color: @color-brand-regular;
        cursor: pointer;
      }

      .default {
        display: flex;
        align-items: center;
        justify-content: center;
        width: 120px;
        height: 100%;
        border-radius: 6px;
        font-weight: bold;
        font-size: 18px;
        text-align: center;
        cursor: pointer;
      }

      .delete-button {
        border: 1px solid #ff6d65;
        color: #ff6d65;
        margin-right: 20px;
      }

      .create-button {
        font-size: 14px;
        height: 100%;
        color: @color-brand-disabled;
        border: 1px solid @color-brand-disabled;
        cursor: not-allowed;

        &.can-create {
          cursor: pointer;
          background-color: @color-brand-regular;
          color: #fff;

          &:hover {
            color: #fff;
            background-color: @color-brand-checked;
          }
        }
      }
    }
  }

  :deep(.ant-table-thead) {
    tr {
      th {
        background-color: #e3ebfc;

        &:first-child {
          border-radius: 14px 0 0 0;
        }

        &:last-child {
          border-radius: 0 14px 0 0;
        }
      }
    }
  }

  :deep(.ant-table-row) {
    cursor: pointer;
    &:hover {
      color: #3d54d9;
    }

    &:nth-child(2n + 1) {
      background-color: #f4f7fc;
    }
    .ant-table-column-sort {
      background-color: unset;
    }
  }
}
</style>
